// server/api/skills.get.ts - 修复版本
import { defineEventHandler, getQuery, getHeader } from "h3";
import { verifyToken } from "../../utils/auth";

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, "authorization");
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      throw createError({
        statusCode: 401,
        statusMessage: "未提供认证令牌",
      });
    }

    const token = authHeader.slice(7);
    const decoded = verifyToken(token);
    if (!decoded) {
      throw createError({
        statusCode: 401,
        statusMessage: "令牌无效或已过期",
      });
    }

    const query = getQuery(event);
    const { username } = query;

    if (!username) {
      throw createError({
        statusCode: 400,
        statusMessage: "需要提供用户名参数",
      });
    }

    // 查询用户是否存在
    const user = await prisma.user.findUnique({
      where: { username: username as string },
    });

    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: "用户不存在",
      });
    }

    // 直接查询技能表，而不是通过用户关系
    const skills = await prisma.skill.findMany({
      where: { userId: user.id },
      orderBy: { createdAt: "desc" },
    });

    return {
      code: 200,
      message: "获取成功",
      data: skills,
    };
  } catch (error: any) {
    console.error("获取技能列表错误:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || "获取失败",
    });
  }
});
